/**
 * @author zhouheng
 * @date 2022年03月03日 13:16
 */

package com.gulimall.search.gulimallsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.vo.SkuEsModel;
import com.gulimall.search.gulimallsearch.constant.EsConstant;
import com.gulimall.search.gulimallsearch.service.ProductSaveService;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    RestHighLevelClient client;

    /*
     * @author zhouheng
     * 用bulk代替index，进行批量保存
     * @date 2022/3/3 0003 14:31
     * @param null 
     * @return null
     */
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        BulkRequest request = new BulkRequest();

        skuEsModels.stream().forEach( skuEsModel -> {
            // 设置es索引 gulimall_product
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            // 设置索引id
            indexRequest.id(String.valueOf(skuEsModel.getSkuId()));
            // json格式
            String jsonString = JSON.toJSONString(skuEsModel);
            indexRequest.source(jsonString, XContentType.JSON);
            // 添加到文档
            request.add(indexRequest);
        });

        BulkResponse bulk = client.bulk(request, RequestOptions.DEFAULT);
        // TODO 是否拥有错误
        boolean hasFailures = bulk.hasFailures();
        if (hasFailures) {
            List<String> collect = Arrays.stream(bulk.getItems()).map(item -> item.getId()).collect(
                Collectors.toList());
            log.error("商品上架错误：{}",collect);
        } else {
            log.error("商品上架成功 spuId = {}", skuEsModels.get(0).getSpuId());
        }

        return hasFailures;
    }
}
